<?php
namespace plugin\ky_shouyin\app\controller;

use support\Request;
use support\Db;
use plugin\ky_shouyin\app\service\MemberCardService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use plugin\ky_shouyin\app\service\PointsService;
use plugin\ky_shouyin\app\service\RechargeService;

class MemberController extends BaseController
{
    public function index()
    {
        try {
            // 获取会员等级列表
            $levels = Db::table('member_level')
                ->where('status', 1)
                ->get();
            
            // 获取门店列表
            $stores = Db::table('store')
                ->where('status', 1)
                ->get();
            
            // 获取统计数据
            $today = date('Y-m-d');
            $weekStart = date('Y-m-d', strtotime('-7 days'));
            $monthStart = date('Y-m-01');
            
            // 今日新增会员
            $todayNew = Db::table('member')
                ->whereDate('created_at', $today)
                ->count();
            
            // 本周新增会员
            $weekNew = Db::table('member')
                ->whereDate('created_at', '>=', $weekStart)
                ->count();
            
            // 今日生日会员
            $todayBirthday = Db::table('member')
                ->whereRaw('DATE_FORMAT(birthday, "%m-%d") = ?', [date('m-d')])
                ->count();
            
            // 本月生日会员
            $monthBirthday = Db::table('member')
                ->whereRaw('DATE_FORMAT(birthday, "%m") = ?', [date('m')])
                ->count();
            
            // 本月未消费会员
            $monthNoConsumption = Db::table('member')
                ->whereNotExists(function($query) use ($monthStart) {
                    $query->select(Db::raw(1))
                        ->from('order')
                        ->whereColumn('order.member_id', 'member.id')
                        ->where('order.status', 1)
                        ->whereDate('order.created_at', '>=', $monthStart);
                })
                ->count();
            
            // 近三月未消费会员
            $threeMonthStart = date('Y-m-d', strtotime('-3 months'));
            $threeMonthNoConsumption = Db::table('member')
                ->whereNotExists(function($query) use ($threeMonthStart) {
                    $query->select(Db::raw(1))
                        ->from('order')
                        ->whereColumn('order.member_id', 'member.id')
                        ->where('order.status', 1)
                        ->whereDate('order.created_at', '>=', $threeMonthStart);
                })
                ->count();
            
            return $this->view('member/index', [
                'levels' => $levels,
                'stores' => $stores,
                'stats' => [
                    'today_new' => $todayNew,
                    'week_new' => $weekNew,
                    'today_birthday' => $todayBirthday,
                    'month_birthday' => $monthBirthday,
                    'month_no_consumption' => $monthNoConsumption,
                    'three_month_no_consumption' => $threeMonthNoConsumption
                ]
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            error_log('Member index error: ' . $e->getMessage());
            // 返回基本视图
            return $this->view('member/index', [
                'levels' => [],
                'stores' => [],
                'stats' => [
                    'today_new' => 0,
                    'week_new' => 0,
                    'today_birthday' => 0,
                    'month_birthday' => 0,
                    'month_no_consumption' => 0,
                    'three_month_no_consumption' => 0
                ]
            ]);
        }
    }

    public function list(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $keyword = $request->input('keyword', '');
        
        $query = Db::table('ky_member')
            ->leftJoin('ky_member_level', 'ky_member.level', '=', 'ky_member_level.id')
            ->leftJoin('ky_member_card', function($join) {
                $join->on('ky_member_card.member_id', '=', 'ky_member.id')
                     ->where('ky_member_card.status', '=', 1);
            })
            ->leftJoin('ky_store', 'ky_member.store_id', '=', 'ky_store.id')
            ->select(
                'ky_member.*',
                'ky_member_level.name as level_name',
                'ky_member_card.card_no',
                'ky_store.name as store_name'
            );
            
        if ($keyword) {
            $query->where(function($query) use ($keyword) {
                $query->where('ky_member_card.card_no', 'like', "%{$keyword}%")
                      ->orWhere('ky_member.name', 'like', "%{$keyword}%")
                      ->orWhere('ky_member.phone', 'like', "%{$keyword}%");
            });
        }
        
        $total = $query->count();
        $members = $query->offset(($page - 1) * $limit)
                        ->limit($limit)
                        ->orderBy('ky_member.id', 'desc')
                        ->get();
                        
        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $total,
            'data' => $members
        ]);
    }

    public function generateCards(Request $request)
    {
        try {
            $prefix = $request->post('prefix', 'VIP');
            $count = $request->post('count', 500);
            
            $service = new MemberCardService();
            $result = $service->generate($prefix, $count);
            
            if ($result['code'] === 0) {
                return json([
                    'code' => 0,
                    'msg' => '生成成功',
                    'data' => ['total' => $count]
                ]);
            } else {
                return json($result);
            }
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '生成失败：' . $e->getMessage()]);
        }
    }

    /**
     * 会员卡列表页面
     */
    public function card()
    {
        return $this->view('member/card');
    }

    /**
     * 获取会员卡列表
     */
    public function cardList(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $cardNo = $request->input('card_no', '');
        $status = $request->input('status', '');
        
        $query = Db::table('ky_member_card')
            ->leftJoin('ky_member', 'ky_member_card.member_id', '=', 'ky_member.id')
            ->select('ky_member_card.*', 'ky_member.name as member_name');
            
        if ($cardNo) {
            $query->where('card_no', 'like', "%{$cardNo}%");
        }
        
        if ($status !== '') {
            $query->where('status', $status);
        }
        
        $total = $query->count();
        $cards = $query->offset(($page - 1) * $limit)
                       ->limit($limit)
                       ->get();
                       
        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $total,
            'data' => $cards
        ]);
    }

    /**
     * 作废会员卡
     */
    public function voidCard(Request $request)
    {
        $id = $request->post('id');
        
        try {
            Db::table('ky_member_card')
                ->where('id', $id)
                ->update(['status' => 2]);
                
            return json(['code' => 0, 'msg' => '作废成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '作废失败：' . $e->getMessage()]);
        }
    }

    /**
     * 批量作废会员卡
     */
    public function batchVoidCards(Request $request)
    {
        $ids = $request->post('ids', []);
        
        try {
            Db::table('ky_member_card')
                ->whereIn('id', $ids)
                ->update(['status' => 2]);
                
            return json(['code' => 0, 'msg' => '批量作废成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '批量作废失败：' . $e->getMessage()]);
        }
    }

    /**
     * 导出会员卡
     */
    public function exportCards(Request $request)
    {
        $ids = $request->get('ids');
        $ids = $ids ? explode(',', $ids) : [];
        
        $query = Db::table('ky_member_card')
            ->leftJoin('ky_member', 'ky_member_card.member_id', '=', 'ky_member.id')
            ->select('ky_member_card.*', 'ky_member.name as member_name');
            
        if (!empty($ids)) {
            $query->whereIn('ky_member_card.id', $ids);
        }
        
        $cards = $query->get();
        
        // 创建Excel
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        
        // 设置表头
        $sheet->setCellValue('A1', '卡号');
        $sheet->setCellValue('B1', '状态');
        $sheet->setCellValue('C1', '使用会员');
        $sheet->setCellValue('D1', '生成时间');
        
        // 写入数据
        $row = 2;
        foreach ($cards as $card) {
            $status = ['未使用', '已使用', '已作废'][$card->status];
            
            $sheet->setCellValue('A'.$row, $card->card_no);
            $sheet->setCellValue('B'.$row, $status);
            $sheet->setCellValue('C'.$row, $card->member_name);
            $sheet->setCellValue('D'.$row, $card->created_at);
            $row++;
        }
        
        // 输出Excel
        $writer = new Xlsx($spreadsheet);
        $filename = '会员卡列表_'.date('YmdHis').'.xlsx';
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        
        $writer->save('php://output');
        exit;
    }

    /**
     * 添加会员
     */
    public function add(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 开启事务
                Db::beginTransaction();
                
                // 验证手机号是否重复
                $exists = Db::table('ky_member')
                    ->where('phone', $data['phone'])
                    ->exists();
                    
                if ($exists) {
                    throw new \Exception('手机号已存在');
                }
                
                // 验证会员卡是否可用
                if (!empty($data['card_no'])) {
                    $card = Db::table('ky_member_card')
                        ->where('card_no', $data['card_no'])
                        ->where('status', 0)
                        ->first();
                        
                    if (!$card) {
                        throw new \Exception('会员卡不存在或已被使用');
                    }
                }
                
                // 添加会员
                $memberId = Db::table('ky_member')->insertGetId([
                    'name' => $data['name'],
                    'phone' => $data['phone'],
                    'level' => $data['level'],
                    'balance' => $data['balance'] ?? 0,
                    'points' => $data['points'] ?? 0,
                    'store_id' => $data['store_id'],
                    'status' => 1,
                    'remark' => $data['remark'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
                
                // 更新会员卡状态
                if (!empty($data['card_no'])) {
                    Db::table('ky_member_card')
                        ->where('card_no', $data['card_no'])
                        ->update([
                            'member_id' => $memberId,
                            'status' => 1,
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                }
                
                // 如果有初始余额，添加充值记录
                if (!empty($data['balance']) && $data['balance'] > 0) {
                    $service = new RechargeService();
                    $rechargeResult = $service->recharge(
                        $memberId,
                        $data['balance'],
                        0,
                        'cash',
                        $data['store_id'],
                        $data['store_id'],
                        $data['store_id'],
                        '开卡赠送'
                    );
                    
                    if ($rechargeResult['code'] !== 0) {
                        throw new \Exception($rechargeResult['msg']);
                    }
                }
                
                Db::commit();
                return json(['code' => 0, 'msg' => '添加成功']);
            } catch (\Exception $e) {
                Db::rollBack();
                return json(['code' => 1, 'msg' => '添加失败：' . $e->getMessage()]);
            }
        }
        
        // 获取门店列表
        $stores = Db::table('ky_store')->where('status', 1)->get();
        // 获取会员等级列表
        $levels = Db::table('ky_member_level')->where('status', 1)->get();
        
        return $this->view('member/add', [
            'stores' => $stores,
            'levels' => $levels
        ]);
    }

    /**
     * 编辑会员
     */
    public function edit(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 更新会员信息
                Db::table('ky_member')
                    ->where('id', $data['id'])
                    ->update([
                        'name' => $data['name'],
                        'phone' => $data['phone'],
                        'level' => $data['level'],
                        'store_id' => $data['store_id'],
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                
                return json(['code' => 0, 'msg' => '编辑成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '编辑失败：' . $e->getMessage()]);
            }
        }
        
        $id = $request->get('id');
        $member = Db::table('ky_member')
            ->where('id', $id)
            ->first();
            
        return $this->view('member/edit', ['member' => $member]);
    }

    /**
     * 删除会员
     */
    public function delete(Request $request)
    {
        $id = $request->post('id');
        
        try {
            // 检查是否有未完成的订单
            $hasOrder = Db::table('ky_order')
                ->where('member_id', $id)
                ->where('status', '<>', 2) // 非已取消状态
                ->exists();
                
            if ($hasOrder) {
                throw new \Exception('该会员有未完成的订单，不能删除');
            }
            
            Db::beginTransaction();
            
            // 作废会员卡
            Db::table('ky_member_card')
                ->where('member_id', $id)
                ->update([
                    'status' => 2,
                    'member_id' => null,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            
            // 删除会员
            Db::table('ky_member')
                ->where('id', $id)
                ->delete();
            
            Db::commit();
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollBack();
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取未使用的会员卡
     */
    public function getUnusedCards(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $cardNo = $request->input('card_no', '');
        
        $query = Db::table('ky_member_card')
            ->where('status', 0)
            ->whereNull('member_id');
            
        if ($cardNo) {
            $query->where('card_no', 'like', "%{$cardNo}%");
        }
        
        $total = $query->count();
        $cards = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('id', 'asc')
                      ->get();
                      
        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $total,
            'data' => $cards
        ]);
    }

    /**
     * 积分记录页面
     */
    public function points()
    {
        return $this->view('member/points');
    }

    /**
     * 获取积分记录列表
     */
    public function pointsList(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $keyword = $request->input('keyword', '');
        $type = $request->input('type', '');
        
        $query = Db::table('ky_points_log')
            ->leftJoin('ky_member', 'ky_points_log.member_id', '=', 'ky_member.id')
            ->select('ky_points_log.*', 'ky_member.name as member_name');
            
        if ($keyword) {
            $query->where(function($query) use ($keyword) {
                $query->where('ky_member.card_no', 'like', "%{$keyword}%")
                      ->orWhere('ky_member.name', 'like', "%{$keyword}%")
                      ->orWhere('ky_member.phone', 'like', "%{$keyword}%");
            });
        }
        
        if ($type !== '') {
            $query->where('ky_points_log.type', $type);
        }
        
        $total = $query->count();
        $logs = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('ky_points_log.id', 'desc')
                      ->get();
                      
        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $total,
            'data' => $logs
        ]);
    }

    /**
     * 会员签到
     */
    public function checkIn(Request $request)
    {
        $memberId = $request->post('member_id');
        
        try {
            // 检查今日是否已签到
            $today = date('Y-m-d');
            $hasChecked = Db::table('ky_points_log')
                ->where('member_id', $memberId)
                ->where('type', 2)
                ->whereRaw('DATE(created_at) = ?', [$today])
                ->exists();
                
            if ($hasChecked) {
                throw new \Exception('今日已签到');
            }
            
            // 获取签到规则
            $rule = Db::table('ky_points_rule')
                ->where('type', 2)
                ->where('status', 1)
                ->first();
                
            if (!$rule) {
                throw new \Exception('未设置签到规则');
            }
            
            // 赠送积分
            $pointsService = new PointsService();
            $result = $pointsService->addPoints(
                $memberId,
                $rule->points,
                2,
                null,
                '每日签到奖励'
            );
            
            if (!$result) {
                throw new \Exception('签到失败');
            }
            
            return json(['code' => 0, 'msg' => '签到成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 积分调整
     */
    public function adjustPoints(Request $request)
    {
        $memberId = $request->post('member_id');
        $points = $request->post('points');
        $description = $request->post('description', '');
        
        try {
            $pointsService = new PointsService();
            $result = $pointsService->addPoints(
                $memberId,
                $points,
                4, // 4表示人工调整
                null,
                $description
            );
            
            if (!$result) {
                throw new \Exception('调整失败');
            }
            
            return json(['code' => 0, 'msg' => '调整成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 充值页面
     */
    public function recharge()
    {
        return $this->view('member/recharge');
    }

    /**
     * 执行充值
     */
    public function doRecharge(Request $request)
    {
        $memberId = $request->post('member_id');
        $amount = $request->post('amount');
        $giveAmount = $request->post('give_amount', 0);
        $paymentMethod = $request->post('payment_method');
        $remark = $request->post('remark', '');
        
        // 获取当前登录员工信息
        $staff = session('staff');
        
        $service = new RechargeService();
        $result = $service->recharge(
            $memberId,
            $amount,
            $giveAmount,
            $paymentMethod,
            $staff['store_id'],
            $staff['id'],
            $remark
        );
        
        return json($result);
    }

    /**
     * 获取充值记录
     */
    public function rechargeLog(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $memberId = $request->input('member_id');
        
        $service = new RechargeService();
        $result = $service->getRechargeLog($memberId, $page, $limit);
        
        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $result['total'],
            'data' => $result['data']
        ]);
    }

    /**
     * 消费记录页面
     */
    public function consumption()
    {
        return $this->view('member/consumption');
    }

    /**
     * 获取消费记录列表
     */
    public function consumptionList(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $keyword = $request->input('keyword', '');
        $memberId = $request->input('member_id');
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        
        $query = Db::table('ky_order')
            ->leftJoin('ky_member', 'ky_order.member_id', '=', 'ky_member.id')
            ->leftJoin('ky_store', 'ky_order.store_id', '=', 'ky_store.id')
            ->leftJoin('ky_staff', 'ky_order.staff_id', '=', 'ky_staff.id')
            ->where('ky_order.status', 1) // 已完成的订单
            ->select(
                'ky_order.*',
                'ky_member.name as member_name',
                'ky_member.phone as member_phone',
                'ky_store.name as store_name',
                'ky_staff.name as staff_name'
            );
            
        if ($keyword) {
            $query->where(function($query) use ($keyword) {
                $query->where('ky_member.card_no', 'like', "%{$keyword}%")
                      ->orWhere('ky_member.name', 'like', "%{$keyword}%")
                      ->orWhere('ky_member.phone', 'like', "%{$keyword}%");
            });
        }
        
        if ($memberId) {
            $query->where('ky_order.member_id', $memberId);
        }
        
        if ($startDate && $endDate) {
            $query->whereBetween('ky_order.created_at', [
                $startDate . ' 00:00:00',
                $endDate . ' 23:59:59'
            ]);
        }
        
        $total = $query->count();
        $orders = $query->offset(($page - 1) * $limit)
                        ->limit($limit)
                        ->orderBy('ky_order.id', 'desc')
                        ->get();
                        
        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $total,
            'data' => $orders
        ]);
    }

    /**
     * 获取会员统计数据
     */
    public function statistics(Request $request)
    {
        $memberId = $request->input('member_id');
        $startDate = $request->input('start_date', date('Y-m-d', strtotime('-30 days')));
        $endDate = $request->input('end_date', date('Y-m-d'));
        
        try {
            // 获取会员信息
            $member = Db::table('ky_member')
                ->leftJoin('ky_member_level', 'ky_member.level', '=', 'ky_member_level.id')
                ->where('ky_member.id', $memberId)
                ->select('ky_member.*', 'ky_member_level.name as level_name')
                ->first();
                
            // 消费统计
            $orderStats = Db::table('ky_order')
                ->where('member_id', $memberId)
                ->where('status', 1)
                ->whereBetween('created_at', [
                    $startDate . ' 00:00:00',
                    $endDate . ' 23:59:59'
                ])
                ->selectRaw('
                    COUNT(*) as order_count,
                    SUM(amount) as total_amount,
                    SUM(points_used) as total_points_used,
                    SUM(points_earned) as total_points_earned
                ')
                ->first();
                
            // 充值统计
            $rechargeStats = Db::table('ky_member_recharge')
                ->where('member_id', $memberId)
                ->whereBetween('created_at', [
                    $startDate . ' 00:00:00',
                    $endDate . ' 23:59:59'
                ])
                ->selectRaw('
                    COUNT(*) as recharge_count,
                    SUM(amount) as total_amount,
                    SUM(give_amount) as total_give_amount
                ')
                ->first();
                
            // 每日消费趋势
            $dailyConsumption = Db::table('ky_order')
                ->where('member_id', $memberId)
                ->where('status', 1)
                ->whereBetween('created_at', [
                    $startDate . ' 00:00:00',
                    $endDate . ' 23:59:59'
                ])
                ->selectRaw('DATE(created_at) as date, COUNT(*) as order_count, SUM(amount) as total_amount')
                ->groupBy('date')
                ->get();
                
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'member' => $member,
                    'order_stats' => $orderStats,
                    'recharge_stats' => $rechargeStats,
                    'daily_consumption' => $dailyConsumption
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取数据失败：' . $e->getMessage()]);
        }
    }

    /**
     * 会员详情页面
     */
    public function detail(Request $request)
    {
        if ($request->method() === 'GET' && $request->get('id')) {
            try {
                // 获取会员详情数据
                $id = $request->get('id');
                $member = Db::table('ky_member')
                    ->leftJoin('ky_member_level', 'ky_member.level', '=', 'ky_member_level.id')
                    ->leftJoin('ky_member_card', function($join) {
                        $join->on('ky_member_card.member_id', '=', 'ky_member.id')
                             ->where('ky_member_card.status', '=', 1);
                    })
                    ->leftJoin('ky_store', 'ky_member.store_id', '=', 'ky_store.id')
                    ->where('ky_member.id', $id)
                    ->select(
                        'ky_member.*',
                        'ky_member_level.name as level_name',
                        'ky_member_card.card_no',
                        'ky_store.name as store_name'
                    )
                    ->first();
                    
                if (!$member) {
                    throw new \Exception('会员不存在');
                }
                
                return json(['code' => 0, 'msg' => 'success', 'data' => $member]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
        }
        
        return $this->view('member/detail');
    }

    /**
     * 选择会员卡页面
     */
    public function selectCard()
    {
        return $this->view('member/select_card');
    }
} 